package org.jeecg.modules.cosmetic.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.cosmetic.model.vo.PicturePathVO;
import org.jeecg.modules.cosmetic.utils.Base64DecodedMultipartFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

/**
 * @author scx
 * @date 2022/7/8 10:51 上午
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/api/file")
@Slf4j
public class FileController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadPath;
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;

    /**
     * 上传
     *
     * @param request
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获取上传文件对象
            MultipartFile file = multipartRequest.getFile("file");
            String uploadUrl;
            if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
                uploadUrl = "http://192.168.88.64:8080/jeecg-boot/" + CommonUtils.uploadLocal(file, uploadPath, uploadPath);
            } else {
                uploadUrl = CommonUtils.upload(file, uploadPath, uploadType);
            }
            return Result.OK(uploadUrl);
        } catch (Exception e) {
            return Result.error("图片上传异常");
        }
    }

    @PostMapping(value = "/upload_base64")
    public Result<?> uploadBase64(@RequestBody PicturePathVO vo) {
        try {
            MultipartFile file = Base64DecodedMultipartFileUtil.base64ToMultipart(vo.getBase64());
            String uploadUrl;
            if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
                uploadUrl = "http://192.168.88.64:8080/jeecg-boot/" + CommonUtils.uploadLocal(file, uploadPath, uploadPath);
            } else {
                uploadUrl = CommonUtils.upload(file, uploadPath, uploadType);
            }
            return Result.OK(uploadUrl);
        } catch (Exception e) {
            return Result.error("图片上传异常");
        }
    }
}
